package repository;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;


/*
 * 使用tomcat连接池来连接数据库
 */
public class DataBaseBeanDBCP implements Serializable {
	private static final long serialVersionUID = 8066006980547744667L;
	/*启用Tomcat连接池连接数据，服务器配置文件在webContent/META-INF/context.xml
	 * DataBaseBean负责获得DataSource对象，并作为BaseDAO类的父类
	 */
	protected DataSource dataSource;
	
	public DataBaseBeanDBCP() {
		try {
			Context initContext = new InitialContext();
			Context envContext = (Context) initContext.lookup("java:/comp/env");
			dataSource = (DataSource) envContext.lookup("jdbc/project");
		}catch (NamingException e) {
			// TODO: handle exception
//			throw new RuntimeException(e);
			System.out.println(e.getMessage());
		}
	}
	
	// 测试数据库是否连接成功
	public boolean isConnectedOK(){
		boolean ok = false;
		// 注意该Connection为java.sql.Connection
		Connection conn = null;
		SQLException ex = null;
		try {
			conn = dataSource.getConnection();
			if(!conn.isClosed()) {
				ok = true;
			}
		}catch (SQLException e) {
			// TODO: handle exception
//			ex = e;
			System.out.println(e.getMessage());
		}finally {
			if (conn != null) {
				try {
					conn.close();
				}catch(SQLException e){
					if(ex == null) {
						ex = e;
					}
				}
				if(ex != null) {
//					throw new RuntimeException(ex);
					System.out.println(ex.getMessage());
				}
			}
		}
		return ok;
	}
}
